<template>
	<view>
		<u-datetime-picker  @confirm="changeTime" :show="InsuranceBuytimeShow" mode="datetime"
			:closeOnClickOverlay="true" @cancel="InsuranceBuytimeShow = false"></u-datetime-picker>
		<u-datetime-picker  @confirm="changeEndTime" :show="InsuranceTimeoutShow" mode="datetime"
			:closeOnClickOverlay="true" @cancel="InsuranceTimeoutShow = false"></u-datetime-picker>
		<u-collapse ref='coll' :value="['1','2']">
			<u-collapse-item name="1" title="基本信息" icon="https://project.gxrunxiang.com/cdn/car.png">
				<u-form ref="uForm" label-width="auto">
					<u-form-item label="保险公司"><u-input v-model="insuranceDetail.InsuranceCompany" /></u-form-item>
					<u-form-item label="保险种类"><u-input v-model="insuranceDetail.InsuranceType" /></u-form-item>
					<u-form-item label="保险金额(元)"><u-input type="digit" v-model="insuranceDetail.InsuranceAmount" /></u-form-item>
					<u-form-item label="车税(元)"><u-input type="digit" v-model="insuranceDetail.InsuranceVehicleTax" /></u-form-item>
					<u-form-item label="合计金额(元)"><u-input type="digit" v-model="insuranceDetail.TotalAmount" /></u-form-item>
					<u-form-item label="保险购买时间" @click="InsuranceBuytimeShow = true" prop="InsuranceBuytime" disabledColor="#ffffff"><u-input disabled
							v-model="insuranceDetail.InsuranceBuytime" /></u-form-item>
					<u-form-item label="保险到期时间" @click="InsuranceTimeoutShow = true" prop="InsuranceTimeout" disabledColor="#ffffff"><u-input disabled
							v-model="insuranceDetail.InsuranceTimeout" /></u-form-item>
					<u-form-item label="期限"><u-input v-model="insuranceDetail.InsurancePeriod" /></u-form-item>
					<u-form-item label="办理人"><u-input v-model="insuranceDetail.Agent" /></u-form-item>
					<u-form-item label="备注"><u--textarea v-model="insuranceDetail.Remark"
							placeholder="请输入内容"></u--textarea></u-form-item>
				</u-form>
			</u-collapse-item>
			<u-collapse-item name="1" title="附件照片" icon="https://project.gxrunxiang.com/cdn/image.png">
				<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
					itype='附件照片' :sizeType='["compressed"]' :maxCount="10"></u-upload>
				<u-album :urls="imagesurls1"></u-album>
			</u-collapse-item>
		</u-collapse>
		<u-button @click="submit">提交</u-button>
		<u-notify ref="uNotify"></u-notify>
	</view>
</template>
<script>
	import {
		baseUrl
	} from '@/common/config.js'
	import {
		mapGetters
	} from 'vuex'

	import {
		addinsurance,
		getinsurancelist,
		insuranceupdate,
		getfilebyoutid
	} from '@/common/api.js'
	export default {
		data() {
			return {
				itypelist: {
					"1": "附件照片",
				},
				insuranceDetail: {},
				fileList1: [],
				imagesurls1: [],
				token: "",
				// dicStatus: [],
				// dicCity: [],
				// showCity: false,
				InsuranceBuytimeShow: false,
				InsuranceTimeoutShow: false,
				user: {},
				notifyData: {
					message: '保存成功',
					type: 'success',
					color: '#ffffff',
					bgColor: '',
					fontSize: 15,
					duration: 3000,
					safeAreaInsetTop: false
				},
			}
		},
		onLoad(option) {
			this.token = uni.getStorageSync("$token")
			if(option.Id){
				this.ischange = true
				this.changeId = option.Id
				this.getchangelist();
				getfilebyoutid(option.Id).then(res => {
					for (var i = 0; i < res.length; i++) {
						if (res[i].MyType == '附件照片') {
							this.imagesurls1.push(`${baseUrl}/SysFile/download?id=${res[i].Id}`)
						}
					}
					setTimeout(() => {
							// console.log(this.$refs.coll)
							this.$refs.coll.init()				
						},
						1000)
				})
			}
			if(option.CarId)
			this.insuranceDetail.CarId = option.CarId
		},
		onShow() {
			let user = JSON.parse(uni.getStorageSync("$userinfo"))
			this.user = user
		},
		methods: {
			dateFormat(date, fmt = "yyyy年MM月dd日") {
				if (date == null) return null;
				if (typeof date === "string") {
					date = date.slice(0, 19).replace("T", " ").replace(/-/g, "/");
					date = new Date(date);
				} else if (typeof date === "number") {
					date = new Date(date);
				}
				var o = {
					"M+": date.getMonth() + 1,
					"[Dd]+": date.getDate(),
					"h+": date.getHours(),
					"m+": date.getMinutes(),
					"s+": date.getSeconds(),
					"q+": Math.floor((date.getMonth() + 3) / 3),
					S: date.getMilliseconds(),
				};
				if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1
					.length));
				for (var k in o) {
					if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? o[
						k] : ("00" + o[k]).substr(("" + o[k]).length));
				}
				return fmt;
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {				console.log(event.name);
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, this.itypelist[event.name])
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, itype) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: `${baseUrl}/SysFile/upload?outid=${this.insuranceDetail.Id||this.user.Id}&type=${itype}`,
						filePath: url,
						name: 'file',
						formData: {
							user: 'test'
						},
						header: {
							"Authorization": `Bearer ${this.token}`
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
							}, 1000)
						}
					});
				})
			},
			submit() {
				if(this.ischange){
					insuranceupdate(this.insuranceDetail).then(res => {
						this.$refs.uNotify.show(this.notifyData)
						setTimeout(() => {
							uni.navigateBack()
						}, 1000)
					})
				}else{
					addinsurance(this.insuranceDetail).then((res) => {
						if (res === true) {
							uni.navigateBack()
						}
					})
				}
				
			},
			changeBuyTime(e){
				const timeFormat = uni.$u.timeFormat
				this.insuranceDetail.BuyTime = timeFormat(e.value, 'yyyy-mm-dd')
				this.buyTimeShow = false
			},
			async getchangelist(){
				let para = {
					Parameters: [{
						FieldName: "Id",
						ConditionalType: "Equal",
						FieldValue: this.changeId
					}],
					orderBys: ["Id"],
				}
				await getinsurancelist(para).then(res => {
					this.insuranceDetail = res.data[0]
				})
			},
			changeTime(e) {
				this.insuranceDetail.InsuranceBuytime = this.dateFormat(e.value, 'yyyy年MM月DD日 hh:mm:ss')
				this.InsuranceBuytimeShow = false
			},
			changeEndTime(e) {
				this.insuranceDetail.InsuranceTimeout = this.dateFormat(e.value, 'yyyy年MM月DD日 hh:mm:ss')
				this.InsuranceTimeoutShow = false
			}
		}
	}
</script>